<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>票务系统 - 功能实现</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; line-height: 1.5; padding: 15px; background-color: #f8f9fa; color: #333; }
        .container { max-width: 800px; margin: auto; }
        .card { background-color: #fff; border: 1px solid #e9ecef; border-radius: 8px; padding: 12px 20px; margin-bottom: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
        h1, h2 { text-align: center; color: #495057; }
        h2 { text-align: left; border-bottom: 1px solid #f1f3f5; padding-bottom: 8px; margin-top: 5px; margin-bottom: 12px; font-size: 1.2em; color: #212529; }
        select, input, button { padding: 8px 12px; margin: 5px; border-radius: 4px; border: 1px solid #ced4da; font-size: 1em; }
        button { cursor: pointer; background-color: #007bff; color: white; border-color: #007bff; font-weight: bold; }
        button:hover { background-color: #0056b3; }
        button:disabled { background-color: #6c757d; cursor: not-allowed; }
        .hidden { display: none; }
        #details, #seats-container, #order-form { margin-top: 15px; }
        pre { background-color: #e9ecef; padding: 12px; border-radius: 4px; white-space: pre-wrap; word-wrap: break-word; font-size: 0.9em; color: #495057; }
    </style>
</head>
<body>

<div class="container">
    <h1>票务系统 - 功能实现</h1>

    <div class="card">
        <h2>步骤 1: 选择一场演出</h2>
        <select id="show-select" onchange="loadShowDetails()">
            <option value="">-- 请选择 --</option>
        </select>
    </div>

    <div id="details" class="card hidden">
        <h2>步骤 2: 查看详情并选择座位</h2>
        <h3>演出信息</h3>
        <pre id="show-info"></pre>
        <h3>票务信息</h3>
        <pre id="ticket-info"></pre>
        <h3>选择座位 (只显示可选座位)</h3>
        <select id="seat-select">
            <option value="">-- 请选择座位 --</option>
        </select>
    </div>

    <div id="order-form" class="card hidden">
        <h2>步骤 3: 确认购票</h2>
        <label>用户ID: <input type="number" id="user-id" value="1"></label>
        <button id="buy-button" onclick="createOrder()"><b>确认买票</b></button>
    </div>

    <div class="card">
        <h2>(独立功能) 退票</h2>
        <label>订单ID: <input type="number" id="refundOrderId" placeholder="输入要退的订单ID"></label>
        <button onclick="refundOrder()"><b>确认退票</b></button>
    </div>

    <div class="card">
        <h2>操作结果</h2>
        <pre id="response-area">这里将显示服务器返回的结果...</pre>
    </div>
</div>

<script>
    const API_BASE_URL = 'http://localhost:8088/api';
    const showSelect = document.getElementById('show-select');
    const seatSelect = document.getElementById('seat-select');
    const responseArea = document.getElementById('response-area');

    let currentShow = null;
    let currentTickets = null;

    window.onload = function() {
        fetch(`${API_BASE_URL}/shows`)
            .then(handleResponse)
            .then(shows => {
                shows.forEach(show => {
                    if (new Date(show.startTime) > new Date()) {
                        const option = document.createElement('option');
                        option.value = show.showId;
                        option.textContent = show.showName;
                        showSelect.appendChild(option);
                    }
                });
            })
            .catch(handleError);
    };

    function loadShowDetails() {
        const showId = showSelect.value;
        if (!showId) {
            document.getElementById('details').classList.add('hidden');
            document.getElementById('order-form').classList.add('hidden');
            return;
        }

        Promise.all([
            fetch(`${API_BASE_URL}/shows/${showId}`).then(handleResponse),
            fetch(`${API_BASE_URL}/shows/${showId}/tickets`).then(handleResponse),
            fetch(`${API_BASE_URL}/shows/${showId}/seats`).then(handleResponse)
        ]).then(([showInfo, ticketInfo, seatInfo]) => {
            currentShow = showInfo;
            currentTickets = ticketInfo;

            document.getElementById('show-info').textContent = JSON.stringify(showInfo, null, 2);
            document.getElementById('ticket-info').textContent = JSON.stringify(ticketInfo, null, 2);

            seatSelect.innerHTML = '<option value="">-- 请选择座位 --</option>';
            seatInfo.forEach(seat => {
                // 【核心修改处】
                if (seat.status === '可选') {
                    const option = document.createElement('option');
                    option.value = JSON.stringify(seat);
                    option.textContent = `座位ID: ${seat.seatId} (${seat.category} - ${seat.rowNum}排${seat.colNum}座)`;
                    seatSelect.appendChild(option);
                }
            });

            document.getElementById('details').classList.remove('hidden');
            document.getElementById('order-form').classList.remove('hidden');
        }).catch(handleError);
    }

    function createOrder() {
        const userId = document.getElementById('user-id').value;
        const selectedSeatJSON = seatSelect.value;

        if (!selectedSeatJSON) return alert('请先选择一个座位');

        const seat = JSON.parse(selectedSeatJSON);

        let price = 0;
        if (currentTickets) {
            const ticket = currentTickets.find(t => t.category === seat.category);
            if (ticket) {
                price = ticket.price;
            }
        }

        const orderData = {
            userId: parseInt(userId),
            showId: seat.showId,
            seatId: seat.seatId,
            showName: currentShow ? currentShow.showName : "",
            category: seat.category,
            rowNum: seat.rowNum,
            colNum: seat.colNum,
            price: price
        };

        const buyButton = document.getElementById('buy-button');
        buyButton.disabled = true;
        buyButton.textContent = '处理中...';

        fetch(`${API_BASE_URL}/orders`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(orderData)
        })
            .then(response => {
                if (!response.ok) throw new Error(`HTTP ${response.status} - ${response.statusText}`);
                return response.text().then(text => text ? JSON.parse(text) : null);
            })
            .then(data => {
                if (data && data.orderId) {
                    showResult(`购票成功！\n` + JSON.stringify(data, null, 2));
                    alert(`购票成功！新的订单ID是: ${data.orderId}`);
                    loadShowDetails();
                } else {
                    showResult("购票失败！座位可能已被抢占。");
                    alert("购票失败！座位可能已被抢占。");
                }
            })
            .catch(handleError)
            .finally(() => {
                buyButton.disabled = false;
                buyButton.textContent = '确认买票';
            });
    }

    function refundOrder() {
        const orderId = document.getElementById('refundOrderId').value;
        if (!orderId) return alert('请输入订单ID');

        const formData = new URLSearchParams();
        formData.append('orderId', orderId);

        fetch(`${API_BASE_URL}/refunds`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: formData
        })
            .then(response => {
                if (!response.ok) throw new Error(`HTTP ${response.status} - ${response.statusText}`);
                return response.text();
            })
            .then(data => {
                showResult(data);
                alert(data);
                if (data.startsWith('退票成功')) {
                    loadShowDetails();
                }
            })
            .catch(handleError);
    }

    function handleResponse(response) {
        if (!response.ok) throw new Error(`HTTP ${response.status} - ${response.statusText}`);
        return response.json();
    }
    function showResult(data) {
        responseArea.textContent = typeof data === 'object' ? JSON.stringify(data, null, 2) : data;
    }
    function handleError(error) {
        responseArea.textContent = '请求失败: ' + error.message;
        console.error('Fetch Error:', error);
    }
</script>

</body>
</html>
